package cn.zyy.dao;

import cn.zyy.entity.Usr;
import cn.zyy.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 持久化层  用于用户数据的持久化  数据库相关操作
 */
public class UserDaoImpl implements UserDao {
    //用户的登录
    public Usr login(Usr usr) {
        Connection conn = JDBCUtil.getConnection();
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            String sql = "select username,password from usr where username = '"+usr.getUsername()+"' and password = '"+usr.getPassword()+"'";
            rs = stmt.executeQuery(sql);
            //处理结果集
            Usr user = null;
            while(rs.next()) {
                String uname = rs.getString(1);
                String pwd = rs.getString(2);
                user = Usr.builder().username(uname).password(pwd).build();
            }
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.closeAll(rs,stmt,conn);
        }
        return null;
    }
    //用户的注册
    public int register(Usr usr) {
        //使用jdbc进行数据的持久化操作  usr
        Connection conn = JDBCUtil.getConnection();
        //获取操作数据库的对象  stmt
        Statement stmt = null;
        try {
            stmt = conn.createStatement();
            Date birth = usr.getBirth();
            Date createTime = usr.getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            String strBirth = sdf.format(birth);
            String strCreateTime = sdfTime.format(createTime);
            String sql = "insert into usr(username,password,birth,create_time) values('"+usr.getUsername()+"','"+usr.getPassword()+"','"+ strBirth +"','"+strCreateTime+"')";
            int line = stmt.executeUpdate(sql);
            return line;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {//释放资源
            JDBCUtil.closeAll(null,stmt,conn);
        }
        return 0;
    }
}
